package Util;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import Interfaces.MsgTimerThreadInterface;
import Util.PriorSafeQueue.Priority;

public class MsgTimerThread {
	private ThreadsPool threadsPool_;
	private PriorSafeQueue queue_;
	private MsgTimerThreadInterface inter_;
	private Timer timerManager_;

	public void setInter(MsgTimerThreadInterface inter) 
	{
		inter_ = inter;
	}

	public MsgTimerThread(int threads) throws ApiException
	{
		if (threads<1)
		{
			Config.logger.error("threads["+threads+"] is less than 1");
			throw new ApiException("threads is less than 1");
		}
		queue_ = new PriorSafeQueue();
		threadsPool_ = new ThreadsPool();
		timerManager_ = new Timer();
		for (int i = 0 ;i < threads;  i++)
		{
			threadsPool_.addThread(new MsgTimerInnerThread());
		}
	}
	
	public void start()
	{
		threadsPool_.startAll();
	}
	
	public void put(Object obj)
	{
		queue_.put(obj);
	}
	
	public void put(Object obj, Priority prior)
	{
		queue_.put(obj, prior);
	}
	
	
	public void addTimer(TimerTask task, Date time, long interval)
	{
		timerManager_.scheduleAtFixedRate(task, time, interval);
	}
	
	public void addTimer(TimerTask task, long delay)
	{
		timerManager_.schedule(task, delay);
	}
	
	public void addTimer(TimerTask task, long delay, long interval)
	{
		timerManager_.schedule(task, delay, interval);
	}
	
	
	class MsgTimerInnerThread extends Thread
	{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			while (true)
			{
				try {
					Object obj = queue_.get();
					if (inter_!=null)
						inter_.deal(obj);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		
	}
}
